// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: jhkim

#include "cc/coin2/exchange/sim/order_v1/backtesting_matcher.h"

namespace coin2::exchange::sim::order_v1 {

void BacktestingMatcher::UpdateFeed(
    const presto::Symbol* symbol,
    const ::fastfeature::FeedMessage& feed) {
  if (!symbol) return;
  if (feed.has_book()) {
    if (feed.book().bid_size() == 0 || feed.book().ask_size() == 0) return;
  }
  holder_->UpdateFeed(symbol, feed);
}

void BacktestingMatcher::SendOrder(
    int64_t order_id,
    std::optional<int64_t> last_time,
    const coin2::exchange::base::order::OrderSpec& spec,
    std::optional<double> submit_max_rate_used_ratio,
    std::optional<double> cancel_max_rate_used_ratio) {
  int sign = 0;
  switch (spec.direction()) {
    case OrderDirection::DIRECTION_BUY:
      sign = 1;
      break;
    case OrderDirection::DIRECTION_SELL:
      sign = -1;
      break;
    default:
      THROW();
  }

  bool ioc = false;
  switch (spec.duration) {
    case OrderDuration::IOC_ORDER:
      ioc = true;
      break;
    case OrderDuration::GTC_ORDER:
      ioc = false;
      break;
    default:
      NOTREACHED() << spec.duration;
  }

  holder_->SendOrder(
      order_id,
      last_time,
      spec.price,
      spec.qty,
      sign,
      spec.post_only,
      spec.tag,
      ioc,
      submit_max_rate_used_ratio,
      cancel_max_rate_used_ratio);

  if (print_simbbo_) {
    SPDLOG_INFO("SIMBBO: {} - {}/{}",
        spec.product, holder_->GetWorkingBbo().first, holder_->GetWorkingBbo().second);
  }
}

void BacktestingMatcher::CancelOrder(int64_t order_id) {
  holder_->CancelOrder(order_id);
}

}  // namespace coin2::exchange::sim::order_v1
